package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
@Slf4j
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Resource
    private ISeckillVoucherService seckillVoucherService;

    @Resource
    private RedisIdWorker redisIdWorker;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    //执行创建订单的动作是在子线程中进行的，获取不到当前主线程的代理类，需要将其设置为属性，以便在子线程中获取
    private IVoucherOrderService proxy;


    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }
    private final BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
    private static final ExecutorService SECKILL_ORDER_SERVICE = Executors.newFixedThreadPool(50);

    //在类加载完成后，提交任务到线程池，执行其中的run方法
    @PostConstruct
    private void init() {
        SECKILL_ORDER_SERVICE.submit(new VoucherOrderHandler());
    }


    private class VoucherOrderHandler implements Runnable {
        String queueName = "stream.orders";
        @Override
        public void run() {
            while (true) {
                try {
                    //1、获取消息队列中的订单信息
                    // XREADGROUP GROUP g1 c2  COUNT 2  BLOCK 2000 STREAMS users >
                    //需要提前在redis中执行xgroup create stream.orders g1 0 MKSTREAM，创建消息队列和消费组
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                            Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),//获取数量为1
                            StreamOffset.create(queueName, ReadOffset.lastConsumed())
                    );

                    //2、判断消息是否获取成功
                    //2.1、获取失败，即当前还没有新的订单要处理，继续进行下次循环
                    if (list == null || list.isEmpty()){
                        continue;
                    }
                    //2.2 获取成功，解析消息
                    MapRecord<String, Object, Object> entries = list.get(0);
                    Map<Object, Object> value = entries.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    //2.3 下单
                    handleVoucherOrder(voucherOrder);

                    //3、ACK确认消息
                    stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    //消息处理异常未确认会存入pending-list,处理pending-list中的消息
                    handlePendingList();
                }
            }
        }
    private void handlePendingList() {
        while (true) {
            try {
                //1.获取pending-list中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS s1 0
                List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                        Consumer.from("g1", "c1"),//创建消费者组
                        StreamReadOptions.empty().count(1),//获取一条
                        StreamOffset.create(queueName, ReadOffset.from("0"))//获取未ack的订单
                );

                //2、判断消息是否获取成功
                //2.1 如果为null，说明pending-list中没有异常消息，结束循环
                if (list == null || list.isEmpty()){
                    break;
                }
                //2.2 获取成功，解析消息
                MapRecord<String, Object, Object> entries = list.get(0);
                Map<Object, Object> value = entries.getValue();
                VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                //2.3 下单
                handleVoucherOrder(voucherOrder);

                //3、ACK确认消息
                stringRedisTemplate.opsForStream().acknowledge(queueName,"g1",entries.getId());
            } catch (Exception e) {
                log.error("处理pending-list订单异常", e);
            }
        }
    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        /**
         * 由于在redis中做了一人一单的判断，同一个用户的多个线程下单时在Lua脚本中会返回1，从而直接返回不能重复下单的提醒
         * 此处加锁是为了防止Redis中出错（尽管不太可能）后兜底
         */
        //1.获取用户
        Long userId = voucherOrder.getUserId();
        //使用Redisson的分布式锁
        // 2.创建锁对象
        RLock redisLock = redissonClient.getLock("lock:order:" + userId);
        // 3.尝试获取锁
        boolean isLock = redisLock.tryLock();
        // 4.判断是否获得锁成功
        if (!isLock) {
            // 获取锁失败，直接返回失败或者重试
            log.error("不允许重复下单！");
            return;
        }
        try {
            //注意：由于是spring的事务是放在threadLocal中，此时的是多线程，事务会失效
            proxy.createVoucherOrder(voucherOrder);
        } finally {
            // 释放锁
            redisLock.unlock();
        }
    }
}


    /**
     *  秒杀券下单
     * @param voucherId 秒杀券id
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        //获取用户id
        Long userId = UserHolder.getUser().getId();
        //生成订单id
        long orderId = redisIdWorker.nextId("order");

        //1、执行Lua脚本
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId)
        );
        int r = result.intValue();

        //2、判断结果Lua脚本返回值是否为0
        if (r != 0) {
            return Result.fail(r == 1 ? "库存步骤":"不允许重复下单");
        }

        //3、创建代理对象
        proxy =(IVoucherOrderService) AopContext.currentProxy();

        //4、返回订单id
        return Result.ok(orderId);
    }


//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //获取 用户
//        Long userId = UserHolder.getUser().getId();
//        //1.执行lua脚本
//        Long result = stringRedisTemplate.execute(
//                SECKILL_SCRIPT,
//                Collections.emptyList(),
//                voucherId.toString(), userId.toString());
//        //2.判断结果是否为0
//        int r = result.intValue();
//        if (r != 0) {
//            //2.1不为0，代表没有购买资格
//            return Result.fail(r == 1 ? "库存不足" : "不能重复下单");
//        }
//        //2.2为0，有购买资格，进行下单，把下单信息保存到阻塞队列中
//        VoucherOrder voucherOrder = new VoucherOrder();
//        //2.3.生成订单id
//        Long orderId = redisIdWorker.nextId("order");
//        voucherOrder.setId(orderId);
//       //2.4.用户id
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//       //2.5.代金券id
//        voucherOrder.setVoucherId(voucherId);
//        //2.6 放入阻塞队列中
//        orderTasks.add(voucherOrder);
//
//        //3获取代理对象
//         proxy = (IVoucherOrderService) AopContext.currentProxy();
//
//        //3.返回订单id
//        return Result.ok(orderId);
//    }


//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        //1.查询优惠券
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        if (seckillVoucher == null) {
//            return Result.fail("优惠券不存在");
//        }
//        //2判断秒杀券是否开始
//        if (seckillVoucher.getBeginTime().isAfter(LocalDateTime.now())) {
//            return Result.fail("秒杀尚未开始");
//        }
//        //3判断秒杀券是否结束
//        if (seckillVoucher.getEndTime().isBefore(LocalDateTime.now())) {
//            return Result.fail("秒杀已结束");
//        }
//        //4判断库存是否充足
//        if (seckillVoucher.getStock() < 1) {
//            return Result.fail("库存不足");
//        }
//        Long userId = UserHolder.getUser().getId();
//        //创建锁对象
//       // SimpleRedisLock lock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        //获取锁
//        //里面没有参数，默认30秒自动释放，不等待，直接返回
//        boolean isLock =lock.tryLock();
//        //判断获取锁成功
//        if (!isLock) {
//            return Result.fail("不允许重复下单");
//        }
//
//        //下面的锁代码，解决一人一单问题，但是存在并发问题
//        //在函数调用处加锁，保证事务提交后再释放锁
//        //synchronized (userId.toString().intern()) {
//        try {
//            //获取代理对象（事务）
//            //获得当前接口的代理对象
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
//            //使用代理对象调用方法
//            return proxy.createVoucherOrder(voucherId);
//            //}
//        }
//        finally {
//            //释放锁
//            lock.unlock();
//        }
//    }
@Transactional
public void createVoucherOrder(VoucherOrder voucherOrder) {
    //1、扣减库存
    boolean success = seckillVoucherService.update()
            .setSql("stock = stock - 1") // set stock = stock - 1
            .eq("voucher_id", voucherOrder.getVoucherId()).gt("stock", 0) // where id = ? and stock > 0
            .update();
    if (!success) {
        // 扣减失败
        log.error("库存不足！");
    }
    //2、保存订单
    save(voucherOrder);
}

}